package controller;

import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import pojo.User;
import service.UserService;
import util.LayData;

import java.util.List;

@Controller
@RequestMapping("/asyncuser")
public class AsyncUserController {

    @Autowired
    private UserService userService;
    @RequestMapping("/tolist")
    public String toList(){
        return "asyncuser/list";
    }
    @RequestMapping("/list")
    @ResponseBody
    public String findAll(User user,@RequestParam(value = "page",defaultValue = "1") int currentPage,
                          @RequestParam(value = "limit",defaultValue = "10") int pageSize, Model model){
        int totalCount = userService.count(user);
        int offset=(currentPage-1)*pageSize;
        List<User> users=userService.findAll(user,offset,pageSize);
        //返回json格式
        LayData layData = new LayData(0,"查询成功",totalCount,users);
        return JSON.toJSONString(layData);
    }

    @RequestMapping("/toadd")
    public String toAdd(){
        return "asyncuser/add";
    }

    @RequestMapping("/addSave")
    @ResponseBody
    public String addUser(User user){
        int result = userService.addUser(user);
        if(result>0){
            //return "redirect:/user/list/1";
            return "success";
        }
        else{
            return "error";
        }
    }



    @RequestMapping("/delete/{id}")
    @ResponseBody
    public String deleteUser(@PathVariable("id") int id){
        int result = userService.deleteUser(id);
        if(result>0){
            return "success";
        }
        else{
            return "error";
        }
    }


    @RequestMapping("/toupdate/{id}")
    public String toUpdate(@PathVariable("id") int id,Model model){
        User user=userService.findUserById(id);
        model.addAttribute("user",user);
        return "asyncuser/update";
    }

    @RequestMapping("/updateSave")
    @ResponseBody
    public String updateUser(User user){
        int result = userService.updateUser(user);
        if(result>0){
            return "success";
        }
        else{
            return "error";
        }
    }

}
